﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using XLua;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class LuaManager : UnitySingleton<LuaManager>
{
    private Dictionary<string, string> m_dicLuaPath;

    private string m_bundleName = "luascript.assetbundle";

    private LuaEnv m_luaEnv;

    public override void Init()
    {
        m_dicLuaPath = new Dictionary<string, string>();
        m_luaEnv = new LuaEnv();
        m_luaEnv.AddLoader(LoadScript);
    }

    public LuaEnv GetLuaEnv()
    {
        if(m_luaEnv == null)
        {
            m_luaEnv = new LuaEnv();
        }
        return m_luaEnv;
    }

    /// <summary>
    /// 获取所有lua文件路径
    /// </summary>
    private void LoadAllLuaFilePath()
    {

    }


    /// <summary>
    /// 加载lua入口文件
    /// </summary>
    public void LoadMainLua()
    {

        //m_luaEnv.DoString(luaCode, luaName + ".lua");
        string luaName = "main";
        execute(string.Format("require ('{0}');", luaName), luaName);
    }

    public void execute(string luaCode, string luaName)
    {
        m_luaEnv.DoString(luaCode, luaName);
    }

    /// <summary>
    /// 加载lua文件
    /// </summary>
    public void LoadLuaScript(string luaName)
    {
        execute(string.Format("require ('{0}');", luaName), luaName);
    }

    private byte[] LoadScript(ref string luaName)
    {
        //string patah = Application.dataPath + "/Lua/" + luaName + ".txt";
        byte[] luaByte = null;
#if UNITY_EDITOR
        //编辑模式下加载lua文件
        string[] assetPaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(m_bundleName, luaName);
        luaByte = System.IO.File.ReadAllBytes(assetPaths[0]);
        int a = 0;
#endif
        if (luaByte == null)
        {
            //非编辑器模式下加载
        }

        return luaByte;
    }


}
    
